package com.way.filemanager.providers;

import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.MatrixCursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.way.filemanager.R;

import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;

public class FolderInfoDBHelper extends SQLiteOpenHelper {
    public static final String DB_TABLE = "dir_name";
    public static final String DB_COLUMN_PATH = "path";
    public static final String DB_COLUMN_NAME = "name";
    private static final String TAG = "FolderInfoDBHelper";
    private static final String DATABASE_NAME = "folder_info.db";
    private static final int DATABASE_VERSION = 1;
    private final String dbDirPath = "/data/data/com.aliyunos.filemanager/databases/";

    public FolderInfoDBHelper(Context context) {
        // TODO Auto-generated constructor stub
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

        InputStream inStream = null;
        FileOutputStream outStream = null;
        try {
            File dbDir = new File(dbDirPath);
            if (!dbDir.exists())
                dbDir.mkdir();
            inStream = context.getResources()
                    .openRawResource(R.raw.folder_info);
            outStream = new FileOutputStream(dbDirPath + "folder_info.db");

            byte[] buffer = new byte[1024];
            int cnt = 0;

            while ((cnt = inStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, cnt);
            }
        } catch (java.io.IOException e) {
            Log.e(TAG, "Copy database exception is " + e.toString());
        } finally {
            try {
                if (inStream != null)
                    inStream.close();

                if (outStream != null)
                    outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE IF NOT EXISTS dir_name (path TEXT PRIMARY KEY, name TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
        onCreate(db);
    }
}
